jQuery(function($){

	// Activate section (it misbehaves when sly is called on hidden sections)
	$(document).on('activated', function( event, sectionId ){
		var $section = $('#'+sectionId);
		switch( sectionId ){
			default:
				// Call sly instances
				$section.find(".slyWrap").each(function(i,e){
					//if( i != 3 ) return;
					var cont = $(this),
						frame = cont.find(".sly"),
						slidee = frame.find("ul"),
						scrollbar = cont.find(".scrollbar"),
						pagesbar = cont.find(".pages"),
						options = frame.data("options"),

						controls = cont.find(".controls"),
						prevButton = controls.find(".prev"),
						nextButton = controls.find(".next"),
						prevPageButton = controls.find(".prevPage"),
						nextPageButton = controls.find(".nextPage");

					options = $.extend( {}, options, {
						scrollBar: scrollbar,
						pagesBar: pagesbar,

						prev: prevButton,
						next: nextButton,
						prevPage: prevPageButton,
						nextPage: nextPageButton,
						disabledClass: 'btn-disabled'
					});
					// Call sly
					frame.sly( options );
				});
		}
		$section.data('examplesLoaded', true);
	});

	// Navigation
	var $nav = $('#nav'),
		$sections = $('#sections').children(),
		activeClass = 'active';
	
	// Activate a section
	function activate( sectionID, initial ){
		sectionID = sectionID && $sections.filter('#'+sectionID).length ? sectionID : $sections.eq(0).attr('id');
		$nav.find('a').removeClass(activeClass).filter('[href=#'+sectionID+']').addClass(activeClass);
		$sections.hide().filter('#'+sectionID).show();
		if( !initial ){
			window.location.hash = '!' + sectionID;
		}
		$(document).trigger('activated', [ sectionID ] );
	}

	// Activate initial section
	activate( window.location.hash.match(/^#!/) ? window.location.hash.substr(2) : 0, 1 );

});